<template>
  <div>
    <a-input-search v-model="names" readOnly unselectable="on" @search="onSearch">
      <a-button
        @click.native="visible = true"
        slot="enterButton"
        :disabled="disabled"
        :icon="searchIcon ? 'search' : ''"
        >{{ searchIcon ? '' : searchBtnText || '选择' }}</a-button
      >
    </a-input-search>

    <!-- 查询窗口 -->
    <a-modal
      :width="modalWidth"
      :visible="visible"
      :title="'选择组织'"
      @ok="handleSelected"
      @cancel="close"
      style="top:50px"
      cancelText="关闭"
    >
      <a-form style="margin-bottom:20px;" layout="inline" @keyup.enter.native="search">
        
        <a-row :gutter="48">
          <template v-if="searchType == 'stdGroup'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.name" placeholder="组织名称" />
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.realname" placeholder="组织负责人" />
            </a-col>
          </template>

          <template v-if="searchType == 'society'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.name" placeholder="社团名称" />
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.realname" placeholder="社团负责人" />
            </a-col>
          </template>

          <template v-if="searchType == 'volunteerTeam'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.name" placeholder="队伍名称" />
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.realname" placeholder="队伍负责人" />
            </a-col>
          </template>

          <template v-if="searchType == 'depart'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.keyWord" placeholder="输入部门名称" />
            </a-col>
          </template>
          <a-col :md="6" :sm="24">
            <a-button @click.native="search">查询</a-button>
          </a-col>
        </a-row>
      </a-form>

      <a-card :loading="loading">
        <a-tree
          v-if="searchType=='depart'"
          @select="onSelect"
          :expandedKeys="iExpandedKeys"
          :checkedKeys="checkedKeys"
          :treeData="dataSource"
        />

        <a-table
          v-else
          ref="table"
          size="middle"
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange , type:'radio'}"
          :loading="loading"
          @change="handleTableChange"
        >
        </a-table>
      </a-card>
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { postAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { find,filter } from 'lodash'
let columnsMap = {
  society: [
    {
      title: '社团名称',
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '负责人',
      align: 'center',
      dataIndex: 'responsibleMan'
    }
  ],
  depart: [],
  stdGroup: [
    {
      title: '组织名称',
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '负责人',
      align: 'center',
      dataIndex: 'director'
    }
  ],
  volunteerTeam:[
    {
      title: '队伍名称',
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '负责人',
      align: 'center',
      dataIndex: 'director'
    }
  ]
}
let urlList = {
  stdGroup: '/org/stdGroup/list',
  society: '/org/society/list',
  depart: '/sys/sysDepart/queryTreeList',
  volunteerTeam: '/volunteerTeam/list'
}

export default {
  name: 'XSelectOrganization',
  props: {
    text:String,
    value: [String, Number],
    disabled: Boolean,
    searchType: {
      type: String,
      default() {
        return 'depart'
      }
    },
    searchIcon: Boolean,
    searchBtnText: String,
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      loading: false,
      visible: false,
      inited: true,
      modalWidth: 800,
      names: '',
      departTree: [],
      queryParam: {},
      dataSource: [],
      checkedKeys:[],
      iExpandedKeys:[],
      selectedRowKeys: [],
      selectionRows: [],
      title: '用户',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      }
    }
  },
  computed: {
    columns() {
      return columnsMap[this.searchType || 'depart']
    },
    url() {
      return urlList[this.searchType || 'depart']
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(nv, ov) {
        if (nv&&nv!=ov) {
          this.inited = false
          this.onSearch()
        } else {
          this.dataSource = []
        }
      }
    },
    text(nv, ov){
      this.names = nv
    },
    searchType(nv, ov) {
      if (nv && nv != ov) {
        this.clear()
      }
    }
  },
  created(){
    this.inited = false
  },
  methods: {
    clear() {
      this.queryParam = {}
      this.dataSource = []
    },
    handleSelected() {
      var data 
      if(this.selectionRows){
        data = this.selectionRows.map(item=>{
          return {id:item.id,name:this.searchType =='depart'?item.departName:item.name}
        })
      }
      
      if(!data.length) return
      let names = []
      let ids = []
      data.forEach(item => {
        names.push(item.name)
        ids.push(item.id)
      })
      ids = ids.join(',')
      this.names = names.join(',')
      this.$emit('onSelected',data)
      this.$emit('input',ids)
      this.$emit('change',ids)
      this.visible = false
    },
    close() {
      this.visible = false
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      for(let k of Object.keys(param)){
        param[k] = `*${param[k]}*`
      }
      Object.assign(param,{actStatus:10},this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    onSelect(selectedKeys, e) {
      let record = Object.assign({}, e.node.dataRef)
      record.name = record.departName
      this.selectedRowKeys = selectedKeys
      this.selectionRows = [record]
    },
    search(){
      let url = '/sys/sysDepart/searchBy'
      let that = this
      if (this.searchType =='depart'&&this.queryParam.keyWord) {
        getAction(url,{ keyWord: this.queryParam.keyWord }).then(res => {
          if (res.success) {
            that.dataSource = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.dataSource.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        this.onSearch()
      }
    },
    setThisExpandedKeys(node) {
      if(node.id==this.value){
        this.selectionRows = [node]
        this.selectedRowKeys = [node.id]
      }
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSearch() {
      this.loadData(1)
    },
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.dataSource = []
      this.loading = true
      let params = this.getQueryParams() //查询条件
      getAction(this.url, params)
        .then(res => {
          if (res.success) {
            if(this.searchType =='depart'){
              //部门全选后，再添加部门，选中数量增多
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                this.dataSource.push(temp)
                this.setThisExpandedKeys(temp)
              }
            }else{
              this.dataSource = res.result.records
              this.ipagination.total = res.result.total
              var selections = find(this.dataSource,{id:this.value})
            }
            // console.log(this.inited,this.selectionRows)
            this.$nextTick(()=>{
              if(!this.inited&&selections){
                this.selectionRows = [selections]
                this.selectedRowKeys = [this.value]
                this.handleSelected()
                this.inited = true
              }
            })
            
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    }
  }
}
</script>

